<template>
  <view class="patient-list w-688rpx mt-40rpx ml-32rpx pb-60rpx mb-137rpx">
    <view class="p_wrap mb-24rpx" v-for="item in patientList" :key="item.id">
      <view class="p_default" v-if="item.isDefault">默认就诊人</view>
      <!-- 就诊卡 -->
      <template v-if="!item.healthCardId">
        <view @click="goHealthDetail(item)">
          <view v-if="fromSource" class="w-full h-336rpx absolute left-0 top-0">
            <image
              class="w-full h-full"
              :src="specUrl('20250529/patient_card.png')"
            ></image>
          </view>
          <view v-else class="w-full h-300rpx absolute left-0 top-0">
            <image
              class="w-full h-full"
              :src="specUrl('20250529/patient_select_card.png')"
            ></image>
          </view>
          <view class="flex p-32rpx relative text-white">
            <view class="flex-1">
              <view class="text-30rpx font-500">{{ getHospitalName }}</view>
              <view class="p_info mt-104rpx">
                <text class="text-36rpx font-500">{{ item.name }}</text>
                <text class="text-28rpx ml-16rpx"
                  >{{ sexEnum(item.sex) }} {{ item.age }}岁</text
                >
              </view>
              <view class="text-28rpx mt-14rpx"
                >登记号：{{ item.registrationCode || "" }}</view
              >
            </view>
            <view class="flex flex-col justify-between ml-12rpx">
              <view class="flex items-center text-30rpx font-500">
                <image
                  class="w-34rpx h-36rpx mr-12rpx"
                  :src="specUrl('20250529/patient_icon.png')"
                ></image>
                就诊卡
              </view>
              <view class="flex justify-end">
                <view
                  v-if="fromSource"
                  class="w-170rpx h-70rpx bg-[#F0A624] rounded-36rpx text-30rpx font-500 text-white center"
                  @click.stop="selectPatient(item)"
                >
                  选择此卡
                </view>
                <template v-else>
                  <PatientCode
                    :patientInfo="item"
                    :show-mange="false"
                  ></PatientCode>
                </template>
              </view>
            </view>
          </view>
        </view>
      </template>
      <!-- 电子健康卡 -->
      <template v-else>
        <view @click="goHealthDetail(item)">
          <view
            v-if="fromSource"
            class="card-face-container from-source-container"
          >
            <image
              class="card-bg"
              :src="specUrl('20250529/health_select_card.png')"
              alt=""
            />
            <view class="card-top-info">
              <view class="card-top-title">
                <image :src="specUrl('20250529/icon2.png')" alt="" />
                <text>电子健康卡</text>
              </view>
              <view class="card-top-org flex-1 ml-14rpx"
                >四川省卫生健康委员会</view
              >
            </view>

            <view class="card-detail-info">
              <view class="card-user-info">
                <view class="card-user-name">{{ item.name }}</view>
                <view class="card-user-id">{{
                  healthCardUtil.maskIdCard(item.certId)
                }}</view>
              </view>
              <view
                class="w-170rpx h-70rpx bg-[#F0A624] rounded-36rpx text-30rpx font-500 text-white center"
                @click.stop="selectPatient(item)"
              >
                选择此卡
              </view>
            </view>
          </view>
          <view v-else class="card-face-container">
            <image
              class="card-bg"
              :src="specUrl('20250529/health_card.png')"
              alt=""
            />
            <view class="card-top-info">
              <view class="card-top-org">四川省卫生健康委员会</view>
              <view class="card-top-title">
                <image :src="specUrl('20250529/icon2.png')" alt="" />
                <text>电子健康卡</text>
              </view>
            </view>

            <view class="card-detail-info">
              <view class="card-user-info">
                <view class="card-user-name">{{ item.name }}</view>
                <view class="card-user-id">{{
                  healthCardUtil.maskIdCard(item.certId)
                }}</view>
              </view>
              <view class="card-qrcode">
                <PatientCode
                  size="154rpx"
                  :border="'none'"
                  :patientInfo="item"
                  :show-mange="false"
                ></PatientCode>
              </view>
            </view>

            <view class="card-footer">
              中华人民共和国国家卫生健康委员会监制
            </view>
          </view>
        </view>
      </template>
    </view>
    <view
      v-if="getLen"
      class="text-28rpx text-[#333333] text-center mt-32rpx mb-24rpx"
    >
      还可绑定
      <text class="text-primary">{{ getLen }}</text>
      张健康卡
    </view>
    <NoData v-if="patientList.length == 0"></NoData>
  </view>
  <BottomButton :disabled="patientList.length == 5" @clickBtn="goAddPatient"
    >+ 添加就诊人</BottomButton
  >
</template>
<script setup name="patient">
import { specUrl } from "@/utils/icon";
import { hospitalName } from "@/config/config";
import { patientlist } from "@/resource/patient";
import { sexEnum } from "@/utils/util";
import { ref, onMounted, computed } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { usePatientStore } from "@/store/patient";
import { toastMsg } from "@/utils/toast";
import healthCard from "../healthCard/static/ElectronicHealthCard";
import healthCardUtil from "@/utils/healthCard/index";
// 主题颜色
import themeStore from "@/store/theme";

const themeColor = themeStore().themeColor;
const patientStore = usePatientStore();
const patientList = ref([]);
const fromSource = ref("");

const MAX_PATIENT = 5;

onLoad((options) => {
  console.log("[options]", options);
  fromSource.value = options.fromSource || "";
});
onShow(() => {
  connectHealthCard();
});

const getHospitalName = computed(() => {
  return hospitalName.replace("互联网医院", "");
});

const getLen = computed(() => {
  return MAX_PATIENT - patientList.value.length;
});

const getList = async () => {
  return new Promise((resolve, reject) => {
    patientlist()
      .then(({ data }) => {
        patientList.value = data;
        updatePatient(data);
        resolve();
      })
      .catch(reject);
  });
};
// 更新就诊人缓存
const updatePatient = (list) => {
  const nowPatient = patientStore.getPatientInfo;
  if (list && list.length > 0) {
    const hasPatient = list.filter((item) => {
      return item.id == nowPatient.id;
    });
    hasPatient.length == 0 && patientStore.setPatient({});
  }
};
const goDetail = (item) => {
  uni.navigateTo({
    url: `/viewPages/patient/detail/index?id=${item.id}`,
  });
};

const goHealthDetail = (item) => {
  uni.navigateTo({
    url: `/viewPages/patient/healthDetail/index?id=${item.id}`,
  });
};

const selectPatient = async (item) => {
  // 医防融合
  if (fromSource.value && fromSource.value == 2) {
    console.log("item", item);
    uni.navigateTo({
      url: `/pagesMedicalPrevention/webview/index?certId=${item.certId}`,
    });
    return;
  }
  //日间手术
  if (fromSource.value && fromSource.value == 5) {
    console.log("item", item);
    try {
      if (!item.patientNo) {
        toastMsg("绑定病案号才能使用");
        return;
      }
      patientStore.setPatient(item);
      patientStore.temporaryStorage(item);
      uni.navigateTo({
        url: `/admissionServiceCenter/certificateList/index`,
      });
    } catch (error) {}
    return;
  }
  //护理随访
  if (fromSource.value && fromSource.value == 6) {
    console.log("item", item);
    patientStore.temporaryStorage(item);
    uni.navigateTo({
      url: `/followPage/home/index`,
    });
    return;
  }
  patientStore.setPatient(item);
  uni.navigateBack();
};

// 添加就诊卡
const goAddPatient = async () => {
  healthCardUtil.create();
};

// 健康卡关联院内
async function connectHealthCard() {
  try {
    healthCardUtil.showLoad();
    const isResult = healthCard.hasResult();
    if (!isResult) {
      await getList();
      healthCardUtil.hideLoad();
      return;
    }
    // 获取健康卡信息
    const res = await healthCard.getInfo();
    console.log("【健康卡信息】", res);
    if (!res.data || !res.data.healthCardId) {
      healthCardUtil.toast("未获取到健康卡数据，请重试");
      return;
    }

    await healthCard.createByHealthCard(res.data);

    patientStore.updatePatient();
    await getList();
    healthCardUtil.hideLoad();
  } catch (error) {
    console.log("【院内建档 异常】", error);
    healthCardUtil.hideLoad(1500);
  }
}
</script>
<style lang="scss">
.p_wrap {
  width: 100%;
  border-radius: 16rpx;
  position: relative;
  overflow: hidden;

  .p_default {
    position: absolute;
    left: 0;
    top: 0;
    width: 162rpx;
    height: 52rpx;
    line-height: 52rpx;
    background: #0b5648;
    border-radius: 16rpx 0rpx 16rpx 0rpx;
    font-weight: 500;
    font-size: 26rpx;
    color: #ffffff;
    text-align: center;
    z-index: 2;
  }
  .card-face-container {
    height: 388rpx;
    width: 100%;
    margin: 0 auto;
    position: relative;
    color: #333333;
    &.from-source-container {
      height: 300rpx;
      .card-detail-info {
        padding: 0 36rpx 0 32rpx;
      }
    }

    .card-bg {
      height: 100%;
      width: 100%;
      position: absolute;
    }

    .card-top-info {
      position: absolute;
      top: 40rpx;
      width: 100%;
      padding: 0 27rpx 0 32rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .card-top-org {
        font-size: 26rpx;
        font-weight: 500;
      }

      .card-top-title {
        display: flex;
        align-items: center;
        font-size: 30rpx;
        color: #2b2b2b;
        font-weight: 500;

        image {
          height: 60rpx;
          width: 60rpx;
          margin-right: 14rpx;
          display: block;
        }
      }
    }

    .card-detail-info {
      position: absolute;
      top: 144rpx;
      width: 100%;
      padding: 0 18rpx 0 32rpx;
      display: flex;
      justify-content: space-between;
      align-items: flex-end;

      .card-user-info {
        font-size: 36rpx;
        color: #2b2b2b;
        font-weight: 500;
        line-height: 50rpx;

        .card-user-id {
          font-size: 30rpx;
          line-height: 42rpx;
          padding-top: 8rpx;
        }
      }

      .card-qrcode {
        background: #ffffff;
        padding: 4rpx;
        position: relative;
      }
    }

    .card-footer {
      position: absolute;
      font-size: 24rpx;
      bottom: 20rpx;
      left: 50%;
      transform: translateX(-50%);
      white-space: nowrap;
      letter-spacing: 0;
      line-height: 25rpx;
      color: #2b2b2b;
    }
  }
}
</style>
